/** 
 * 初始化
 */
$(function(){
	__init_workspace_body();
	__init_category_body();
	__init_goods_list_body();
	__init_menu_body();
	__init_config_mg();
});

/**
 * 加载功能页面
 */
function loadPage(url)
{
	$("#workspace > iframe").attr("src",URL_FMT(url));
};

/**
 * 打开弹出的EUI窗口
 */
function GBL_EUI_WIN(cfg)
{
	var key = "#" + (cfg.id?cfg.id:("_SYS_UI_WIN_"+(new Date()).getTime()));
	if("open"==cfg.act)
	{
		if($(key).length==0)
		{
			$("<div>",{id:key.substring(1)}).appendTo(document.body);
			$(key).window({
				title:cfg.title,
				width:cfg.width,
				height:cfg.height,
				modal:true,cache:false,minimizable:false,maximizable:false,collapsible:false,resizable:false,closed:true,
				onClose:function(){
					$(key).remove();
				}
			});
		}
		$(key).window({href:cfg.url});
		$(key).window("open");
	}else
		$(key).window("close");
};
/**
 * 初始化主页工作台
 */
function __init_workspace_body(){
	if(!IS_PGOBJ('#workspace-body')) return;
	
	var h = $(document).height()-10;
	$("#_categoryShowArea").height(h);
	$("#_categoryShowArea .csab").height(h-24);
	// 绑定关闭事件
	$("#_categoryShowArea .csah").click(function(){
		$("#_categoryShowArea").hide(500);
	});
	//注册类别展现树
	$("#catRoot").tree({
		"url":URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryCategoryForTree.do?parentCid=0"),
		"loadFilter":function(dat,p){
			if(dat.status=='success')
			{
				__PRI_LOADING(0);
				return dat.values;
			}else{
				__PRI_LOADING(0);
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		},
        onBeforeExpand:function(node){
        	var catTree = $('#catRoot');
        	var child = catTree.tree("getChildren",node.target);
			if(!child || child.length==0)
			{
            	catTree.tree('options').url = URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryCategoryForTree.do?parentCid="+node.id);
			}
        },
        onClick:function(node){
			loadPage(URL_FMT(SVR_CTX_PATH + "/super/goods-list.jsp?cid="+node.id));
			$("#_categoryShowArea").hide(500);
        }
    });
};
/**
 * 打开商品类别的浮动层
 */
function openCategorys()
{
	$("#_categoryShowArea").show();
};

/**
 * 初始化商品类别管理页面
 */
function __init_category_body(){
	if(!IS_PGOBJ('#category-body')) return;
	var h = $(document).height()-10;
	$("#mgArea .catBox").height(h);
	$("#mgArea .catBox .catList").height(h-30);
	
	// 注册树
	$("#localCat").tree({
		"url":URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryCategoryForTree.do?parentCid=0"),
		"loadFilter":function(dat,p){
			if(dat.status=='success')
			{
				__PRI_LOADING(0);
				return dat.values;
			}else{
				__PRI_LOADING(0);
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		},
        onBeforeExpand:function(node){
        	var catTree = $('#localCat');
        	var child = catTree.tree("getChildren",node.target);
			if(!child || child.length==0)
			{
            	catTree.tree('options').url = URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryCategoryForTree.do?parentCid="+node.id);
			}
        }
    });
    
	$("#taobaoCat").tree({
		"loadFilter":function(dat,p){
			if(dat.status=='success')
			{
				__PRI_LOADING(0);
				return dat.values;
			}else{
				__PRI_LOADING(0);
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		},
        onBeforeExpand:function(node){
            $('#taobaoCat').tree('options').url = URL_FMT(SVR_CTX_PATH + "/manage/superAct!categorySync.do?parentCid="+node.id);     
        },
		onDblClick:function(node){
            var child = $('#taobaoCat').tree('getChildren',node.target);
            if(child && child.length>0)
            	$('#taobaoCat').tree('toggle',node.target);
            else
            	$('#taobaoCat').tree('reload',node.target);
		}
    });
};
/**
 * 重新载入本地商品类别
 */
function reloadLocalCategory()
{
	$("#localCat").tree({"url":URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryCategoryForTree.do?parentCid=0")});
};
/**
 * 展开所有的本库商品类别
 */
function collapseAllLocalCategory()
{
	var catTree = $("#localCat");
	catTree.tree("collapseAll");
};
/**
 * 删除选择的类别
 */
function removeLocalCategory()
{
	var node = $("#localCat").tree("getSelected");
	if(!node) return;
	
	$.messager.confirm("确认提示","您是否确认删除选择的类别以及旗下的子类别数据吗？",function(r){
		if(r)
		{
			GBL_JSON_POST(URL_FMT(SVR_CTX_PATH + "/manage/superAct!categoryRemove.do"),
				{'cid':node.id},
				function(dat){
					if(dat.status=='success')
					{
						$.messager.alert('温馨提示',dat.values,"info");
						$("#localCat").tree({"url":URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryCategory.do?parentCid=0")});
					}else{
						$.messager.alert('温馨提示',dat.values,"warning");
					}
				}
			);
		}
	});
};

/**
 * 淘宝类别同步
 */
function startCategorySync()
{
	__PRI_LOADING(1);
	$("#taobaoCat").tree({"url":URL_FMT(SVR_CTX_PATH + "/manage/superAct!categorySync.do?parentCid=0")});
};

/**
 * 添加淘宝类别到本地库
 */
function appendCategoryToLocal()
{
	var node = $("#taobaoCat").tree("getSelected");
	var isparent = node.attributes.isParent;
	var child = $('#taobaoCat').tree('getChildren',node.target);
    var hasChild = (child && child.length>0);
    
    var catLs = [];
    if(isparent)
	{
		if(hasChild)
		{
			for(var i in child)
			{
				catLs.push("{\"cid\":\"" + child[i].id + "\",\"name\":\"" + child[i].text + "\",\"parentCid\":\"" + child[i].attributes.parentCid + "\",\"sortOrder\":\"" + child[i].attributes.sortOrder + "\"}");
			}
			catLs.reverse();
			submitCategoryToLocal(node,catLs);
		}else{
			$.messager.confirm("温馨提示","没有展开叶子节点的类目数据，是否继续保存？",function(ret){
				if(ret){
					submitCategoryToLocal(node,catLs);
				}
			});
		}
	}
	else
		submitCategoryToLocal(node,catLs);

};
/**
 * 提交保存选定的类别到本地库
 */
function submitCategoryToLocal(node,catLs)
{
	while(node)
	{
		catLs.push("{\"cid\":\"" + node.id + "\",\"name\":\"" + node.text + "\",\"parentCid\":\"" + node.attributes.parentCid + "\",\"sortOrder\":\"" + node.attributes.sortOrder + "\"}");
		node = $("#taobaoCat").tree("getParent",node.target);
	}
	catLs.reverse();
	
	GBL_JSON_POST(URL_FMT(SVR_CTX_PATH + "/manage/superAct!categorySave.do"),
		{'catList':"["+ catLs.join(",") +"]"},
		function(dat){
			if(dat.status=='success')
			{
				$.messager.alert('温馨提示',dat.values,"info");
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};

/**
 * 初始化商品列表管理页面
 */
function __init_goods_list_body()
{
	if(!IS_PGOBJ('#goods-list-body')) return;
	var w = $(document).width()-10;
	var h = $(document).height()-10;
	$("#goodsArea").height(h);
	$("#goodsList").height(h-22);
	$("#goodsList .itembox").width(248*(parseInt(w/248))+12);
	
	queryTaobaoGoods(1);
};
/**
 * 查询淘宝的商品
 */
function queryTaobaoGoods(page)
{
	var cid = $("input[name='cid']").val();
	if($.trim(cid)=='')
		return;
	var keyword = $("#btnBar input[name='keyword']").val();
		
	GBL_JSON_POST(URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryGoodsFromTaobao.do"),
		{'cid':cid,'rows':30,'page':page,'searchString':$.trim(keyword)},
		function(dat){
			if(dat.status=='success')
			{
				if(dat.values)
				{
					displayGoodsForUi(dat.values);
				}
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};
/**
 * 在页面上展示商品
 * @param {} goodsList
 */
function displayGoodsForUi(retDat)
{
	var goods = retDat.root;
	if(!goods)
	{
		$.messager.alert("提示","查询没有数据返回！","info");
		return;
	}
	var gls = $("#goodsList .itembox");
	var html = "";
	for(var i in goods)
	{
		var s = goods[i]["sellerCreditScore"];
		var sico = "";
		if(s<=0)
			sico = "未知";
		else if(s<=5)
			sico = "<img src='"+S_SVR_CTX_PATH+"/images/super/score/s_red_"+s+".gif'/>";
		else if(s<=10)
			sico = "<img src='"+S_SVR_CTX_PATH+"/images/super/score/s_blue_"+(s-5)+".gif'/>";
		else if(s<=15)
			sico = "<img src='"+S_SVR_CTX_PATH+"/images/super/score/s_cap_"+(s-10)+".gif'/>";
		else if(s<=20)
			sico = "<img src='"+S_SVR_CTX_PATH+"/images/super/score/s_crown_"+(s-15)+".gif'/>";

		html += "<div id='ITEM_"+goods[i]["numIid"]+"' class='fl item'>";
		html += "<a href='"+goods[i]["clickUrl"]+"' target='_blank'\"><span class='lntxt n_ping tal'>"+goods[i]["title"]+"</span></a><br/>";
		html += "<a href='"+goods[i]["clickUrl"]+"' target='_blank' title=\""+ GBL_title_tip(goods[i]["title"],0,0,true) +"\">";
		html += "<img class='g' src='"+ goods[i]["picUrl"] +"_b.jpg'/>";
		html += "</a>";
		html += "<ul class='tal'>";
		html += " <li><span class='lb'>商品价格：</span><span>"+ goods[i]["price"] +"</span></li>";
		html += " <li><span class='lb'>淘客佣金：</span><span class='n_red'>"+ goods[i]["commission"] +"</span></li>";
		html += " <li><span class='lb'>佣金比率：</span><span class='n_org'>"+ goods[i]["commissionRate"]/100 +"%</span></li>";
		html += " <li><span class='lb'>累计支出佣金：</span><span>"+ goods[i]["commissionVolume"] +"</span></li>";
		html += " <li><span class='lb'>累计成交量：</span><span>"+ goods[i]["commissionNum"] +"</span></li>";
		html += " <li><span class='lb'>30天内成交量：</span><span>"+ goods[i]["volume"] +"</span></li>";
		html += " <li>----------------</li>";
		html += " <li><span class='lb'>商品所在地：</span><span>"+ goods[i]["itemLocation"] +"</span></li>";
		html += " <li><span class='lb'>卖家信用等级：</span><span>"+ sico +"</span></li>";
		html += "</ul>";
		html += "<form id='FRM_"+goods[i]["numIid"]+"' class='hide'>";
		html += " <input type='hidden' name='numIid' value='"+ GBL_title_tip(goods[i]["numIid"]) +"'/>";
		html += " <input type='hidden' name='title' value='"+ GBL_title_tip(goods[i]["title"]) +"'/>";
		html += " <input type='hidden' name='price' value='"+ goods[i]["price"] +"'/>";
		html += " <input type='hidden' name='commission' value='"+ goods[i]["commission"] +"'/>";
		html += " <input type='hidden' name='commissionRate' value='"+ goods[i]["commissionRate"] +"'/>";
		html += " <input type='hidden' name='commissionNum' value='"+ goods[i]["commissionNum"] +"'/>";
		html += " <input type='hidden' name='commissionVolume' value='"+ goods[i]["commissionVolume"] +"'/>";
		html += " <input type='hidden' name='itemLocation' value='"+ goods[i]["itemLocation"] +"'/>";
		html += " <input type='hidden' name='nick' value='"+ goods[i]["nick"] +"'/>";
		html += " <input type='hidden' name='picUrl' value='"+ goods[i]["picUrl"] +"'/>";
		html += " <input type='hidden' name='clickUrl' value='"+ goods[i]["clickUrl"] +"'/>";
		html += " <input type='hidden' name='shopClickUrl' value='"+ goods[i]["shopClickUrl"] +"'/>";
		html += " <input type='hidden' name='sellerCreditScore' value='"+ goods[i]["sellerCreditScore"] +"'/>";
		html += " <input type='hidden' name='volume' value='"+ goods[i]["volume"] +"'/>";
		html += "</form>";
		html += "<a href='javascript:void(0)' class='addbtn' onclick=\"menuWinOpen('"+ goods[i]["numIid"] +"')\">添加</a>";
		html += "</div>";
	}
	gls.html(html);
	
	// 计算分页
	$("#btnBar .page_nav").html(GBL_toNavPage(retDat.page,retDat.totalPage,15,"queryTaobaoGoods"));
};
/**
 * 打开菜单选择窗口
 */
function menuWinOpen(numiid)
{
	$("input[name='curNumIid']").val(numiid);
 	GBL_EUI_WIN({
 		act:"open",
 		id:"menusWin",
 		title:"选择加入到菜单、标签",
 		width:800,height:500,
 		url:URL_FMT(SVR_CTX_PATH+"/super/goods-list-class-win.jsp")
 	});
};
/**
 * 菜单选择窗口的初始化
 */
function __init_goods_list_class_win()
{
	// 注册树
	__PRI_LOADING(1);
	$("#menuTree").tree({
		"loadFilter":function(dat,p){
			if(dat.status)
			{
				if(dat.status=='success')
				{
					__PRI_LOADING(0);
					return dat.values;
				}else{
					__PRI_LOADING(0);
					$.messager.alert('温馨提示',dat.values,"warning");
				}
			}
			else
				return dat;
		},
        onBeforeExpand:function(node){
        	var catTree = $('#menuTree');
        	var child = catTree.tree("getChildren",node.target);
			if(!child || child.length==0)
			{
            	catTree.tree("options").url = URL_FMT(SVR_CTX_PATH + "/system/sysDatAct!loadMenuFromCache.do?pmnid="+node.id);
			}
        }
    });
	// 请求加载菜单树的数据
	GBL_JSON_GET(URL_FMT(SVR_CTX_PATH + "/system/sysDatAct!loadMenuFromCache.do"),{'pmnid':0},
		function(dat){
			if(dat.status=='success')
			{
				$("#menuTree").tree({data:dat.values});
				loadTags();
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};
/**
 * 加载tag
 */
function loadTags(isReload)
{
	if(1==isReload) $("#tagArea").empty();
	if(IS_PGOBJ($("#tagArea span"))) return;
	// 请求加载TAG的数据
	GBL_JSON_GET(URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryAllTags.do"),null,
		function(dat){
			if(dat.status=='success')
			{
				$.each(dat.values,function(i,n){
					var ckey = "#_tag_class_"+n.mnid;
					if(!IS_PGOBJ(ckey))
					{
						var cdiv = $("<div>",{id:ckey.substring(1),sno:n.mnid,style:"margin-bottom:8px;border:1px solid #24A3F6;"});
						$("<h3 style='color:#c080ff;border-bottom:1px solid #F2F6FF;width:90%;line-height:22px;margin:3px;'>"+n.typeName+"</h3>").appendTo(cdiv);
						if(i==0)
							$("#tagArea").append(cdiv);
						else{
							$.each($("#tagArea div"),function(idx,ee){
								var sno = parseInt($(ee).attr("sno"));
								if(n.mnid>sno)
									$(ee).after(cdiv);
								else
									$(ee).before(cdiv);
							});
						}
					}
					$(ckey).append("<span tagid='"+n.tagid+"' name='"+n.name+"' onclick=\"selTag(this)\">"+n.name+"</span>");
				});
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};

/**
 * 选择TAG
 */
function selTag(tag)
{
	$(tag).toggleClass("spanSel");
};

/**
 * 打开tag添加窗口
 */
function tagAddWinOpen()
{
 	GBL_EUI_WIN({
 		act:"open",
 		id:"tagsWin",
 		title:"新建TAG标签",
 		width:400,height:135,
 		url:URL_FMT(SVR_CTX_PATH+"/super/goods-list-tag-add-win.jsp")
 	});
};

/**
 * 提交TAG的添加
 */
function submitTagAdd()
{
	var tagName = $("#tagAddForm input[name='tagName']").val();
	if($.trim(tagName)=='')
	{
		alert("请输入一个有效的标签!");
		return;
	}
	tagName = tagName.replace(/(\"|\'|\s)+/g,"");
	
	var mnid = $("#tagAddForm select[name='mnid']").val();
	
	GBL_JSON_POST(URL_FMT(SVR_CTX_PATH + "/manage/superAct!submitTagAdd.do"),{'mnid':mnid,'tagName':tagName},
		function(dat){
			if(dat.status=='success')
			{
				GBL_EUI_WIN({act:'close',id:"tagsWin"});
				loadTags(1);
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};

/**
 * 添加一个商品
 */
function submitGoodsAdd()
{
	var cid = $("input[name='cid']").val();
	var numiid = $("input[name='curNumIid']").val();
	if($.trim(cid)=='' || $.trim(numiid)=='')
		return;
	var node = $("#menuTree").tree("getSelected");
	if(!node) return;
	var mnid = node.id;
	var tagNames="";
	$.each($("#tagArea span.spanSel"),function(i,n){
		tagNames += "," + $(n).attr("name");
	});
	if(tagNames!='') tagNames = tagNames.substring(1);
	
	var dat = $("#FRM_"+numiid).serialize();
	dat = dat+"&cid="+cid+"&mnid="+mnid+"&tags="+encodeURIComponent(tagNames);
	GBL_JSON_POST(URL_FMT(SVR_CTX_PATH + "/manage/superAct!submitGoods.do"),dat,
		function(dat){
			if(dat.status=='success')
			{
				GBL_EUI_WIN({act:'close',id:"menusWin"});
				$("#ITEM_"+numiid).hide();
				$.messager.show({"title":"添加结果","msg":"商品添加成功，请继续添加！","height":80,"timeout":1000});
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};

/**
 * 初始化菜单管理页面
 */
function __init_menu_body(){
	if(!IS_PGOBJ('#menu-mg')) return;
	var h = $(document).height()-10;
	$("#mgArea .catBox").height(h);
	$("#mgArea .catBox .catList").height(h-30);
	
	// 注册树
	$("#menuMaintainTree").tree({
		"url":URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryMenuForTree.do?pmnid=0"),
		"loadFilter":function(dat,p){
			if(dat.status=='success')
			{
				__PRI_LOADING(0);
				return dat.values;
			}else{
				__PRI_LOADING(0);
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		},
		onLoadSuccess:function(node,data){
			// 树加载完后加载tag标签
			loadTags();
		},
        onBeforeExpand:function(node){
        	var catTree = $('#menuMaintainTree');
        	var child = catTree.tree("getChildren",node.target);
			if(!child || child.length==0)
			{
            	catTree.tree('options').url = URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryMenuForTree.do?pmnid="+node.id);
			}
        },
        onClick:function(node){
			loadMenuRelateTags(node.id);
        }
    });
};
/**
 * 子菜单项维护
 */
function subMenuItemMaintain(act)
{
	var node = $("#menuMaintainTree").tree("getSelected");
	if(!node) return;
	if('add'==act)
	 	GBL_EUI_WIN({
	 		act:"open",
	 		id:"menuItemMaintainWin",
	 		title:"菜单项维护",width:380,height:250,
	 		url:URL_FMT(SVR_CTX_PATH+"/super/menu-mg-menuitem-win.jsp?pmnid="+node.id+"&mnid=0")
	 	});
	else if('mod'==act)
	 	GBL_EUI_WIN({
	 		act:"open",
	 		id:"menuItemMaintainWin",
	 		title:"菜单项维护",width:380,height:250,
	 		url:URL_FMT(SVR_CTX_PATH+"/super/menu-mg-menuitem-win.jsp?pmnid="+node.attributes.pmnid+"&mnid="+node.id)
	 	});
	else if('del'==act)
	{
		$.messager.confirm("提示","是否删除选择的菜单项?",function(r){
			if(r)
			{
				var menuTree = $("#menuMaintainTree");
				var pnode = menuTree.tree("getParent",node.target);
				var childCount = pnode?menuTree.tree("getChildren",pnode.target).length:0;
				
				GBL_JSON_GET(URL_FMT(SVR_CTX_PATH + "/manage/superAct!removeMenuItem.do"),{'mnid':node.id},
						function(dat){
							if(dat.status=='success')
							{
								if(childCount>1){
									menuTree.tree("reload",pnode.target);
								}else
									menuTree.tree({"url":URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryMenuForTree.do?pmnid=0")});
							}else{
								$.messager.alert('温馨提示',dat.values,"warning");
							}
						}
					);
			}
		});
	}
};
/**
 * 在弹出窗口中加载子菜单项
 */
function __init_menuitem_Maintain_win(mnid)
{
	if(mnid==0) return;
	GBL_JSON_GET(URL_FMT(SVR_CTX_PATH + "/manage/superAct!getMenuByMnid.do"),{'mnid':mnid},
			function(dat){
				if(dat.status=='success')
				{
					$("#menuItemForm").json2form({data:dat.values});
				}else{
					$.messager.alert('温馨提示',dat.values,"warning");
				}
			}
		);
};
/**
 * 保存子菜单项
 */
function submitMenuItemSave()
{
	var fdat = $("#menuItemForm").form2json();
	GBL_JSON_POST(URL_FMT(SVR_CTX_PATH + "/manage/superAct!submitMenuItemSave.do"),fdat,
		function(dat){
			if(dat.status=='success')
			{
				GBL_EUI_WIN({act:'close',id:"menuItemMaintainWin"});
				
				var menuTree = $("#menuMaintainTree"); 
				var node = menuTree.tree("getSelected");
				// mnid为0相当于新增的情况
				if(fdat["mnid"]==0)
				{
					if(node.attributes.isParent){
						var child = menuTree.tree("getChildren",node.target);
						if(!child || child.length==0)
							menuTree.tree("expand",node.target);
						else
							menuTree.tree("reload",node.target);
					}else
						menuTree.tree({"url":URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryMenuForTree.do?pmnid=0")});
				}else{
					var pnode = menuTree.tree("getParent",node.target);
					if(pnode)
						menuTree.tree("reload",pnode.target);
					else
						menuTree.tree({"url":URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryMenuForTree.do?pmnid=0")});
				}
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};
/**
 * tag 维护
 */
function tagMaintain(act)
{
	if('add'==act)
		tagAddWinOpen();
	else if('link'==act)
	{		
		var node = $("#menuMaintainTree").tree("getSelected");
		if(!node) return;
		if($("#tagArea span.spanSel").length==0) return;
		
	 	GBL_EUI_WIN({
	 		act:"open",
	 		id:"tagsLinkWin",
	 		title:"关联TAG标签",
	 		width:450,height:250,
	 		url:URL_FMT(SVR_CTX_PATH+"/super/goods-list-tag-link-win.jsp?mnid="+node.id)
	 	});
	}
	else if('delink'==act)
	{
		var node = $("#menuMaintainTree").tree("getSelected");
		if(!node) return;
		var anySpanSel = $("#tagArea span.spanSel");
		if(anySpanSel.length==0) return;
		$.messager.confirm('确认','是否解除选择的TAG标签？',function(r){
			if(r){
				var tagids = [];
				$.each(anySpanSel,function(i,e){
					var  _span = $(e);
					var tagid = _span.attr("tagid");
					tagids.push(tagid);
				});
				GBL_JSON_GET(URL_FMT(SVR_CTX_PATH + "/manage/superAct!removeMenuTagLinks.do"),{'mnid':node.id,'tagids':tagids.join(",")},
					function(dat){
						if(dat.status=='success')
						{
							loadMenuRelateTags(node.id);
						}else{
							$.messager.alert('温馨提示',dat.values,"warning");
						}
					}
				);
			}
		});
	}
	else if('del'==act)
	{
		var anySpanSel = $("#tagArea span.spanSel");
		if(anySpanSel.length==0) return;
		$.messager.confirm('确认','是否删除选择的TAG标签？',function(r){
			if(r){
				var tagids = [];
				$.each(anySpanSel,function(i,e){
					var  _span = $(e);
					var tagid = _span.attr("tagid");
					tagids.push(tagid);
				});
				GBL_JSON_GET(URL_FMT(SVR_CTX_PATH + "/manage/superAct!removeTags.do"),{'tagids':tagids.join(",")},
					function(dat){
						if(dat.status=='success')
						{
							loadTags(1);
						}else{
							$.messager.alert('温馨提示',dat.values,"warning");
						}
					}
				);
			}
		});
	}
};
/**
 * 加载菜单项相关的TAG
 */
function loadMenuRelateTags(mnid)
{
	GBL_JSON_GET(URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryMenuItemRelateTags.do"),{'mnid':mnid},
		function(dat){
			if(dat.status=='success')
			{
				$("#tagArea span").removeClass("spanHasSel spanSel");
				$("#tagArea span").removeAttr("sno tagShortName somp");
				
				if(!isEmpty(dat.values))
				{
					for(var i=dat.values.length-1;i>=0;i--)
					{
						var e = dat.values[i];
						var selSpan = $("#tagArea span[tagid="+e.tagid+"]");
						selSpan.addClass("spanHasSel");
						selSpan.attr({sno:e.sno , tagShortName:e.tagShortName , somp:e.somp});
						//selSpan.parent().prepend(selSpan);
					}
				}
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};
/**
 * 在弹出窗口中初始化关联标签
 */
function __init_tag_link_win()
{
	var anySpanSel = $("#tagArea span.spanSel");
	$("#tagLinkForm input[name='tags']").val(anySpanSel.length);
	$.each(anySpanSel,function(i,e){
		var  _span = $(e);
		var tagid = _span.attr("tagid");
		$("#tagLinkForm ul").append("<li>" +
				"<input type='hidden' name='tagid_"+i+"' value='"+tagid+"' class='tf1'/>" +
				"<label>"+_span.attr("name")+"：</label>" +
				"<input type='text' name='sno_"+tagid+"' value='"+toStr(_span.attr("sno"))+"' class='tf1'/>" +
				"<input type='text' name='tagShortName_"+tagid+"' value='"+toStr(_span.attr("tagShortName"))+"' class='tf2'/>" +
				"<input type='text' name='somp_"+tagid+"' value='"+toStr(_span.attr("somp"))+"' class='tf3'/>" +
				"</li>");
	});
};
/**
 * 提交保存标签关联
 */
function submitTagsLink()
{
	var fdat = $("#tagLinkForm").form2json();
	GBL_JSON_POST(URL_FMT(SVR_CTX_PATH + "/manage/superAct!submitMenuTagsLinkSave.do"),fdat,
		function(dat){
			if(dat.status=='success')
			{
				GBL_EUI_WIN({act:'close',id:"tagsLinkWin"});
				loadMenuRelateTags(fdat.mnid);
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};
/**
 * 初始化配置管理页面
 */
function __init_config_mg()
{
	if(!IS_PGOBJ('#config-mg')) return;
	configDatagridInit();
	cacheListDatagridInit();
};
/**
 * 配置项管理数据表格初始化
 */
function configDatagridInit()
{
	// 初始化列表
	$("#configList").datagrid({
		height:$("#configList").parent().height(),
		sortName:"c_id",
		sortOrder:"asc",
		remoteSort:true,
        pagination:true,
		pageList:[15,50,100],
		rownumbers:false,
		autoRowHeight:true,
		singleSelect:false,
		url: URL_FMT(SVR_CTX_PATH + "/manage/superAct!queryAllSysConfig.do"),
		frozenColumns:[[
		  	{field:'cb',checkbox:true}
		]],
	    columns:[[
	        {field:'c_id',hidden:true},
	        {field:'c_name',title:'配置项名称',width:200,align:'center',formatter:GBL_title_tip},
	        {field:'c_value',title:'配置项的内容',width:300,align:'center',formatter:GBL_title_tip},
	        {field:'c_description',title:'描述',width:300,align:'center',formatter:GBL_title_tip},
	        {field:'c_create_tm',title:'创建时间',width:120,align:'center',formatter:function(val,rdat,ridx){
        		return val.substring(0,10);
        	}},
	        {field:'c_status',title:'状态',width:45,align:'center',formatter:function(val,rdat,ridx){
        		if(val==1)
        			return "正常";
        		else
        			return "停用";
        	}}
		]],
		loadFilter:function(dat,p){
			if(dat.status=='success')
			{
				return dat.values;
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		},
		onClickRow:function(ridx,rdata){
			$("#configList").datagrid("unselectAll");
			$("#configList").datagrid("selectRow",ridx);
		},
		toolbar:[{
			text:'新增配置项',
			iconCls:'icon-add',
			handler:function(){
			 	GBL_EUI_WIN({
			 		act:"open",
			 		id:"sysConfigWin",
			 		title:"添加系统配置项",
			 		width:450,height:200,
			 		url:URL_FMT(SVR_CTX_PATH+"/super/config-mg-add-win.jsp?c_id=0")
			 	});
			}
		},'-',{
			text:'编辑配置项',
			iconCls:'icon-edit',
			handler:function(){
				var rows = $('#configList').datagrid('getSelections');
				if(rows && rows.length==1)
				{
				 	GBL_EUI_WIN({
				 		act:"open",
				 		id:"sysConfigWin",
				 		title:"编辑系统配置项",
				 		width:500,height:200,
				 		url:URL_FMT(SVR_CTX_PATH+"/super/config-mg-add-win.jsp?c_id="+rows[0]["c_id"])
				 	});
				}
			}
		},'-',{
			text:'删除配置项',
			iconCls:'icon-remove',
			handler:function(){
				var rows = $('#configList').datagrid('getSelections');
				if(rows && rows.length>0)
				{
					$.messager.confirm('删除提示',"是否删除选中的系统配置项？<br/><span class='n_red'>注意：删除后不可恢复</span>",function(r){
						if(r)
						{
							var cf = window.confirm("您确定真的要删除吗？");
							if(!cf) return;
							
							var cids = [];
							$.each(rows,function(i,e){
								cids.push(e["c_id"]);
							});
							GBL_JSON_POST(URL_FMT(SVR_CTX_PATH + "/manage/superAct!removeSysConfigs.do"),{'cids':cids.join(",")},
									function(dat){
										if(dat.status=='success')
										{
											$('#configList').datagrid('reload');
										}else{
											$.messager.alert('温馨提示',dat.values,"warning");
										}
									}
								);
						}
					});
				}
			}
		}],
	});
};
/**
 * 缓存管理数据表格初始化
 */
function cacheListDatagridInit()
{
	// 初始化列表
	$("#cacheList").datagrid({
		height:$("#cacheList").parent().height(),
		remoteSort:false,
        pagination:false,
		pageList:[15,50,100],
		rownumbers:false,
		autoRowHeight:true,
		singleSelect:false,
		frozenColumns:[[
		  	{field:'cb',checkbox:true}
		]],
	    columns:[[
	        {field:'cacheCode',hidden:true},
	        {field:'cacheName',title:'缓存名称',width:250,align:'center',formatter:GBL_title_tip}
		]],
		loadFilter:function(dat,p){
			if(dat.status=='success')
			{
				return dat.values;
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		},
		onClickRow:function(ridx,rdata){
			$("#cacheList").datagrid("unselectAll");
			$("#cacheList").datagrid("selectRow",ridx);
		},
		toolbar:[{
			text:'刷新选择的缓存',
			iconCls:'icon-reload',
			handler:function(){
				var rows = $('#cacheList').datagrid('getSelections');
				if(rows && rows.length>0)
				{
					var cacheCodes = [];
					$.each(rows,function(i,e){
						cacheCodes.push(e["cacheCode"]);
					});
					GBL_JSON_GET(URL_FMT(SVR_CTX_PATH + "/svl/cacheReflash"),{'cacheCodes':cacheCodes.join(",")},
							function(dat){
								if(dat.status=='success')
								{
									$.messager.alert('温馨提示','刷新成功！',"info");
									loadLocalCacheData();
								}else{
									$.messager.alert('温馨提示',dat.values,"warning");
								}
							}
						);
				}
			}
		}],
	});
	// 加载cache数据
	loadLocalCacheData();
};

function loadLocalCacheData()
{
	var datSet = {'total':4,'rows':[
	                                {cacheCode:'sysCfgDataCache',cacheName:'系统配置项数据缓存'},
	                                {cacheCode:'areaDataCache',cacheName:'省市区基础数据缓存'},
	                                {cacheCode:'menuDataCache',cacheName:'系统菜单数据缓存'},
	                                {cacheCode:'tagDataCache',cacheName:'前台展示用tag数据缓存'}]};
	$("#cacheList").datagrid("loadData",{'status':'success',values:datSet});
};


/**
 * 初始化配置项的编辑WIN
 */
function __init_sys_config_win(c_id)
{
	if(c_id==0) return;
	var row = $('#configList').datagrid('getSelected');
	$("#sysConfigForm").json2form({data:row});
	$("#sysConfigForm input[name='c_name']").attr("disabled","disabled");
};
/**
 * 保存配置项
 */
function submitSysConfigSave()
{
	var fdat = $("#sysConfigForm").form2json();
	GBL_JSON_POST(URL_FMT(SVR_CTX_PATH + "/manage/superAct!submitSysConfigSave.do"),fdat,
		function(dat){
			if(dat.status=='success')
			{
				GBL_EUI_WIN({act:'close',id:"sysConfigWin"});
				$('#configList').datagrid('reload');
			}else{
				$.messager.alert('温馨提示',dat.values,"warning");
			}
		}
	);
};